var currentMonDate = '';


		var FC = $.fullCalendar; // a reference to FullCalendar's root namespace
		var View = FC.View;      // the class that all views must inherit from
		var CustomView;          // our subclass

		var dayIDs = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
		var planScheduInfos = [];
		var currentDate = '';  //当天日期
		var viewType = '';//视图类型
		var empNameInfoList = [];  //换班人员信息
		var chgShiftDate = [];
		var chgShiftRec = []; //被换班人员
		var chgShiftDateHtml = '';
		var applicant = null;
		var receiver = null;
		var dayoff = 0;
		var chgDate = '';
		var viewFlag = false;
		// var dropDownHtml = '';


		CustomView = View.extend({ // make a subclass of View
			scroller: null,
			dayGridClass: FC.DayGrid,
			dayGrid: null,
			test: 'success',

			planScheduInfo: null, //排班数据
			currentOnSetDate: '', //当前查询起始时间
			expirationDate: '',  //当前查询结束时间


			headContainerEl: null, // div that hold's the dayGrid's rendered date header
			headRowEl: null, // the fake row element of the day-of-week header
			rowCoordCache: null,
			colCoordCache: null,

			initialize: function () {
				this.dayGrid = this.instantiateDayGrid();
				this.scroller = new FC.Scroller({
					// 	// overflowX: 'hidden',
					// 	// overflowY: 'auto'
				});
			},

			instantiateDayGrid: function () {

				var subclass = this.dayGridClass.extend(customDayGridMethods);

				return new subclass(this);
			},

			setRange: function (range) {
				View.prototype.setRange.call(this, range); // call the super-method

				this.dayGrid.setRange(range);

				// var rangeCopy =  range;
				if (/month/.test(range.intervalUnit)) {
					currentOnSetDate = range.start.startOf('week').format();
					console.log("currentOnSetDate : " + currentOnSetDate);
					if (range.end.weekday()) {  //如果当月最后一日不是周日
						expirationDate = range.end.add(1, 'week').startOf('week').format();
						console.log("expirationDate : " + expirationDate);
					} else {
						expirationDate = range.end.add(1, 'day').startOf('week').format();
						console.log("expirationDate : " + expirationDate);
					}
				} else {
					currentOnSetDate = range.start.startOf('week').format(); //获取当前查询起始时间
					console.log("currentOnSetDate : " + currentOnSetDate);
					expirationDate = range.end.format();
					console.log("expirationDate : " + expirationDate);
				}
				viewType = this.type;
				viewFlag = true;   //切换视图时 重载排班人员信息 不然周视图和月视图只会有一种视图模式人员班次信息 导致调班任务不正确
				empNameInfoList = []; // 切换视图时 不清空内存人员班次数据  会有两种视图模式人员班次信息 导致调班任务不正确
				chgShiftRec = [];
				fetchPlanScheduInfo(currentOnSetDate, expirationDate, viewType);
			},
			//生成范围时间
			computeRange: function (date) {
				var range = View.prototype.computeRange.call(this, date);
				console.log(range.intervalUnit);
				chgShiftDateHtml = '';


				// var end = range.end;

				return range;
			},

			//生成表单数据
			renderDates: function () {

				this.el.addClass('fc-basic-view').html(this.renderSkeletonHtml());
				this.renderHead();  //表头


				//布置HTML布局
				var dayGridContainerEl = $('<div class="fc-day-grid-container"></div>');
				var dayGridEl = $('<div class="fc-day-grid" />').appendTo(dayGridContainerEl);
				this.el.find('.fc-body > tr > td').append(dayGridContainerEl);

				this.dayGrid.setElement(dayGridEl);
				renderBodyDatas();  //表格数据体
				this.dayGrid.rowEls = this.el.find('.fc-row');
				this.dayGrid.cellEls = this.el.find('.fc-day');

				this.dayGrid.rowCoordCache = new FC.CoordCache({
					els: this.dayGrid.rowEls,
					isVertical: true
				});
				this.dayGrid.colCoordCache = new FC.CoordCache({
					els: this.dayGrid.cellEls.slice(0, this.colCnt), // only the first row
					isHorizontal: true
				});
			},


			setHeight: function (height, isAuto) {
				// responsible for adjusting the pixel-height of the view. if isAuto is true, the
				// view may be its natural height, and `height` becomes merely a suggestion.
			},

			renderEvents: function (events) {
				// reponsible for rendering the given Event Objects
			},

			destroyEvents: function () {
				// responsible for undoing everything in renderEvents
			},

			renderSelection: function (range) {
				this.dayGrid.renderSelection(span);
			},

			destroySelection: function () {
				this.dayGrid.unrenderSelection();
			},

			renderSkeletonHtml: function () {
				return '' +
					'<table>' +
					'<thead class="fc-head">' +
					'<tr>' +
					'<td class="fc-head-container ' + this.widgetHeaderClass + '">' +
					'<div class="fc-row ' + this.widgetHeaderClass + '">' +
					'<table>' +
					'<thead>' +
					'<tr class="fc-date-num"></tr>' +
					'<tr class="fc-date-str"></tr>' +
					'</thead>' +
					'</table>' +
					'</div>' +
					'</td>' +
					'</tr>' +
					'</thead>' +
					'<tbody class="fc-body">' +
					'<tr>' +
					'<td class="' + this.widgetContentClass + '"></td>' +
					'</tr>' +
					'</tbody>' +
					'</table>';
			},
			renderHead: function () {
				this.renderHeadDateCellsHtml();
				this.headContainerEl = this.el.find('.fc-head-container');
				this.headRowEl = this.headContainerEl.find('.fc-row');
			},

			prepareHits: function () {
				this.dayGrid.prepareHits();
			},


			releaseHits: function () {
				this.dayGrid.releaseHits();
			},

			renderHeadDateCellsHtml: function () {
				var htmlstr = [];
				var htmlnum = [];
				var col, date;

				var headline = '<th class="fc-day-header ' + this.widgetHeaderClass + ' headline" rowspan="2"> 姓名</th>'


				for (col = 0; col < this.dayGrid.colCnt; col++) {
					date = this.dayGrid.getCellDate(0, col);
					htmlstr.push(this.renderHeadDateCellStrHtml(date));
					htmlnum.push(this.renderHeadDateCellNumHtml(date));
				}

				this.el.find('.fc-date-num').html(headline + htmlnum.join(''));
				this.el.find('.fc-date-str').html(htmlstr.join(''));
			},

			renderHeadDateCellStrHtml: function (date, colspan, otherAttrs) {
				// var view = this.view;
				var html = '';
				var attr = '';
				html += '<td class="fc-day-header ' + this.widgetHeaderClass + ' fc-' + dayIDs[date.day()] + ' str"' +
					(this.rowCnt === 1 ? ' data-date="' + date.format('YYYY-MM-DD') + '"' : '') + '>';
				if (this.type == 'customWeek') {
					attr = this.buildGotoAnchorHtml(  //可省略
						{ date: date, forceOff: this.rowCnt > 1 || this.colCnt === 1 },

						FC.htmlEscape(date.format('ddd')) // inner HTML
					)
				} else {
					attr = this.buildGotoAnchorHtml(  //可省略
						{ date: date, forceOff: this.rowCnt > 1 || this.colCnt === 1 },

						FC.htmlEscape(date.format(this.dayGrid.colHeadFormat)).substr(-1) // inner HTML
					)
				}
				html += attr + '</td>';
				return html;
			},

			renderHeadDateCellNumHtml: function (date, colspan, otherAttrs) {

				return '' +
					'<th class="fc-day-header ' + this.widgetHeaderClass + ' fc-' + dayIDs[date.day()] + ' num"' +
					(this.rowCnt === 1 ? ' data-date="' + date.format('YYYY-MM-DD') + '"' : '') + '>' +
					date.format().substr(-2) +
					'</th>';
			},

			suc: function () {
				//				alert(1111)
			}

		});


		//生成表格数据
		function renderBodyDatas() {
			if (planScheduInfos.length == 0) {
				//...
			}
			var html = '';
			var row;

			html += this.renderDayRowHtml(planScheduInfos);
			$('.fc-day-grid').html(html);
		}

		function renderDayRowHtml(planScheduInfos) {
			var classes = ['fc-row', 'fc-week', 'fc-widget-content'];
			if (viewType == 'customMonth') {
				classes.push('customMonth');
			}

			return '' +
				'<div class="' + classes.join(' ') + '">' +
				'<table>' +
				this.renderContentTrHtml(planScheduInfos) +
				'</table>' +
				'</div>';

		}


		function renderContentTrHtml(planScheduInfos) {
			var htmls = [];
			var col;

			for (col = 0; col < planScheduInfos.length; col++) {
				htmls.push(this.renderBgCellHtml(planScheduInfos[col]));
			}
			return htmls.join('');
		}

		function renderBgCellHtml(planScheduInfo) {
			// var classes = this.getDayClasses(date);
			var classes = [];
			var htmls = [];
			if (viewType == 'customMonth') {
				classes.push('customMonth');
			}

			classes.unshift('fc-day', 'fc-widget-content');

			var department = '<tr class="department"><td colspan="33">' + planScheduInfo.dept + '</td></tr>';
			// htmls.push(department);
			for (col = 0; col < planScheduInfo.data.length; col++) {
				var data = planScheduInfo.data[col];
				department += '<tr><td class="headline' + '">' + data.uname + '</td>';
				for (row = 0; row < data.shiftInfo.length; row++) {
					department += '<td class="' + classes.join(' ') + '" style="' + assemblyColor(data.shiftInfo[row]) + '">' + data.shiftInfo[row]; + '</td>';
				}
				department += '</tr>';
			}
			return department;
		}

		function assemblyColor(shift) {
			if (shift == '休') {
				return '';
			}
			if (shift == '日' || shift == '早') {
				return 'background-color:#5E91EC;color:white';
			}
			if (shift == '中') {
				return 'background-color:#4FCB8D;color:white';
			}
			if (shift == '夜') {
				return 'background-color:#FF7C46;color:white';
			}
			if (shift == '全') {
				return 'background-color:#fb7c7c;color:white';
			}
		}

		var customDayGridMethods = {

		};



		//获取排班信息
		function fetchPlanScheduInfo(currentOnSetDate, expirationDate, viewType) {
			$.ajax({
				url: '/plan/planShift',
				data: {
					post: '',
					reqShiftDate: currentOnSetDate,    //查询日期 起
					reqShiftEndDate: expirationDate,  //查询日期 止
					planShiftType: viewType                //视图类型
				},
				type: 'POST',
				dataType: 'json',
				async: false,
				success: function (data) {
					if (data.code == 'success') {
						planScheduInfos = data.data;

					} else if (data.code == 'info') {
						// renderNewPlanScheduInfo();
						planScheduInfos.length = 0;  //清空上轮数据
						toastr[data.code](data.message);
					} else {
						toastr[data.code](data.message);
					}
				},
				error: function (xhr, state, errorThrown) {
					toastr['error']('系统异常！');
				}
			});
		}

		//生成新排班纪录
		function renderNewPlanScheduInfo(currentOnSetDate, expirationDate, viewType) {
			var mon = moment().startOf('week');
			var next = moment().startOf('week').add(2, 'weeks').format('YYYY-MM-DD');
			console.log(next);
			if (currentOnSetDate < mon.format('YYYY-MM-DD')) {   //如果要生成排班表的起始日期小于当前周一的日期 
				toastr['info']('过去的就过去了 ...');
				//			}else if(currentOnSetDate >= next){  //如果要生成排班表的起始日期在下下周
				//				alert("着什么急 ...");
			} else {
				$.ajax({
					url: '/plan/renderShift',
					data: {
						post: '',
						reqShiftDate: currentOnSetDate,
						reqShiftEndDate: expirationDate,
						planShiftType: viewType
					},
					type: 'POST',
					dataType: 'json',
					async: false,
					success: function (data) {
						if (data.code == 'success') {
							planScheduInfos = data.data;
						} else {
							toastr[data.code](data.message);
						}
					},
					error: function (xhr, state, errorThrown) {
						toastr['error']('系统异常！');
					}

				});
			}
		}



		function renderPlanScheduData() {
			renderNewPlanScheduInfo(currentOnSetDate, expirationDate, viewType);
			this.renderBodyDatas();
		}

		function changeShift() {
			$('#changeShifts').modal('toggle');   //打开模态框
		}

		function calendar() {



			$('#calendar').fullCalendar({
				header: {
					left: 'prev,next today',
					center: 'title',
					right: 'customWeek,customMonth'
				},
				defaultView: 'customWeek',
				defaultDate: currentDate,
				navLinks: true, // can click day/week names to navigate views
				editable: false, //鼠标点击报错注释监听代码 还要将此属性改为false  this.dayDragListener = this.buildDayDragListener();
				eventLimit: true, // allow "more" link when too many events
				schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source',  //scheduler 商业项目许可证  (须开源)
				jsonObject: [
					{
						title: 'All Day Event',
						start: '2019-01-08'
					},
					{
						title: 'Long Event',
						start: '2016-09-07',
						end: '2016-09-10'
					},
				],
				events: [],
				planScheduInfos: planScheduInfos
			});

		}

		function getEmpInfo(postinfo) {

		}

		function renderSelectHtml(chgShiftDataArr) {
			if (chgShiftDataArr || chgShiftDataArr.length != 0) {
				var dropDownHtml = '';
				for (var i = 0; i < chgShiftDataArr.length; i++) {
					dropDownHtml += "<li class='chgShiftRec-li'><a href='#' name='" + chgShiftDataArr[i].uname + "' uid='" + chgShiftDataArr[i].uid + "' postInfo='" + chgShiftDataArr[i].postInfo + "'>" + chgShiftDataArr[i].uname + " " + chgShiftDataArr[i].postInfo + "</a></li><li role='separator' class='divider'></li>"
				}
				return dropDownHtml;
			}
		}

		/* 

		*/
		function renderChgShiftDateHtml(onsetDate, days) {
			var temp, date, dayISO, day;
			for (var i = 0; i < days; i++) {
				temp = onsetDate.add(1, 'day');
				date = temp.format('YYYY-MM-DD');
				dayISO = temp.format('dddd');
				day = temp.isoWeekday();
				chgShiftDateHtml += "<li><a href='#' date='" + date + "' dayiso='" + dayISO + "' day='" + day + "'>" + date + "   " + dayISO + "</a></li><li role='separator' class='divider'></li>"
			}
			$('.chgShiftDate-select').html(chgShiftDateHtml);
		}


		/* 
			@param applicant 申请者
			@param receiver  接受者
			@param dayoff    日期偏移量
		 */
		function exchangeShiftData(applicant, receiver, dayoff, chgDate) {
			if (!applicant || !receiver || !dayoff) {
				toastr['warning']('表单信息不完整！');
				return;
			}	
			dayoff -= 1;
			var appShiftInfo = applicant.shiftInfo;
			var recShiftInfo = receiver.shiftInfo;
			var returndata = [];
			if (viewType == 'customWeek') {
				var tempShift = appShiftInfo[dayoff];
				appShiftInfo[dayoff] = recShiftInfo[dayoff];
				recShiftInfo[dayoff] = tempShift;

				returndata.push({ psid: applicant.shiftInfoBean.psids, planShiftInfo: appShiftInfo.join(',') });
				returndata.push({ psid: receiver.shiftInfoBean.psids, planShiftInfo: recShiftInfo.join(',') });
			} else {
				var dayInMon = moment(chgDate).date() - 1; //当前选中调班日期在数组中位置

				chgDate = moment(chgDate).startOf('week').format('YYYY-MM-DD');
				var chgDateInMon = moment(chgDate).date() - 1;  //当前选中调班日期的周一日期的数组位置

				var planShiftDates = applicant.shiftInfoBean.planShiftDate.split(',');
				var index = planShiftDates.indexOf(chgDate);
				if (index < 0) {
					toastr['warning']('当前不存在此班次！');
					return;
				}

				var tempShift = appShiftInfo[dayInMon];
				appShiftInfo[dayInMon] = recShiftInfo[dayInMon];
				recShiftInfo[dayInMon] = tempShift;

				appShiftInfo = appShiftInfo.slice(chgDateInMon, chgDateInMon + 7); //从当前选中调班日期的周一开始截取
				recShiftInfo = recShiftInfo.slice(chgDateInMon, chgDateInMon + 7);

				var appPsidArry = applicant.shiftInfoBean.psids.split(',');
				var recPsIdArry = receiver.shiftInfoBean.psids.split(',');
				var appPsId = appPsidArry[index];
				var recPsId = recPsIdArry[index];

				returndata.push({ psid: appPsId, planShiftInfo: appShiftInfo.join(',') });
				returndata.push({ psid: recPsId, planShiftInfo: recShiftInfo.join(',') });
			}
			$.ajax({
				url: '/plan/chgShift',
				data: JSON.stringify(returndata),
				type: 'POST',
				dataType: 'json',
				contentType: 'application/json;charset=utf-8',
				success: function (data) {
					if (data.code == 'success') {
						// planScheduInfos = data.data;
						toastr[data.code](data.message);
//						$('.modal-backdrop').removeClass('in').addClass('out');
//					//							setTimeout(function () { location.reload(true); }, 1000);	
						setTimeout(function () { 
							location.reload();
							window.location.replace('http://localhost:10016/gcstation#planScheduling');

						}, 1000);
					} else {
						toastr[data.code](data.message);
					}
				},
				error: function (xhr, state, errorThrown) {
					toastr['error']('系统异常！');
				}
			});


		}

		function getEmpData(uid, chgShiftRec) {
			emp = chgShiftRec.filter(function (element) {
				return element.uid == uid;
			})
			return emp[0];
		}

		function renderChgShiftRec(empPostInfo){
				chgShiftRec = empNameInfoList.filter(function (element) {
						return element.postInfo == empPostInfo
				})
				return chgShiftRec;
		}

		$(document).ready(function () {

			$('#chgShiftEmp').on('show.bs.dropdown', function () {
				if (viewFlag) {
					// if (!empNameInfoList || empNameInfoList.length == 0) {
					for (var i = 0; i < planScheduInfos.length; i++) {
						for (var j = 0; j < planScheduInfos[i].data.length; j++) {
							empNameInfoList.push(planScheduInfos[i].data[j]);
						}
					}
					var empDropDownHtml = renderSelectHtml(empNameInfoList);
					$('.emp-select').html(empDropDownHtml);
					viewFlag = false;
					// }
				}
			})

			$("body").delegate(".emp-select a", "click", function () {
				var target = $(event.target);
				var empPostInfo = target.attr('postInfo');
				var uid = target.attr('uid');
				$('.chgShiftEmpBtnText').text(target.attr('name') + ' ' + target.attr('postInfo'));
				$('.chgShiftRecBtnText').text('点击选择')

				if (!chgShiftRec || chgShiftRec.length == 0) {
					chgShiftRec = renderChgShiftRec(empPostInfo);
				} else if (chgShiftRec[0].postInfo != empPostInfo) {
					chgShiftRec = renderChgShiftRec(empPostInfo);
				}
				applicant = getEmpData(uid, chgShiftRec);

				var chgShiftRecTemp = chgShiftRec.filter(function (element) {
						return element.uid != uid
				})
				var recDropDownHtml = renderSelectHtml(chgShiftRecTemp);
				$('.chgShiftRec-select').html(recDropDownHtml);
			});


			$('#chgShiftDate').on('show.bs.dropdown', function () {
				if (!chgShiftDateHtml || chgShiftDateHtml == '') {
					if (viewType == 'customWeek') {
						var onsetDate = moment(currentOnSetDate).add(-1, 'day');
						renderChgShiftDateHtml(onsetDate, 7);
					} else {
						var monthStart = moment(currentOnSetDate).add(1, 'week').startOf('month');
						var days = monthStart.daysInMonth();
						monthStart.add(-1, 'day');
						renderChgShiftDateHtml(monthStart, days);
					}
				}
			})

			$("body").delegate(".chgShiftDate-select a", "click", function () {
				var target = $(event.target);
				dayoff = target.attr('day');
				chgDate = target.attr('date');   //.replace(/\//g, '-');
				$('.chgShiftDateBtnText').text(chgDate + ' ' + target.attr('dayiso'));
			});

			$("body").delegate(".chgShiftRec-select a", "click", function () {
				var target = $(event.target);
				var uid = target.attr('uid');
				receiver = getEmpData(uid, chgShiftRec);
				$('.chgShiftRecBtnText').text(target.attr('name') + ' ' + target.attr('postInfo'));
			});

			$(".postBtn").on("click", function () {
				exchangeShiftData(applicant, receiver, dayoff, chgDate);
			});

			//清空表单数据
			$('.modal').on('hidden.bs.modal', function () {
				$('.chgShiftEmpBtnText').text("点击选择");
				$('.chgShiftDateBtnText').text("点击选择");
				$('.chgShiftRecBtnText').text("点击选择");
				applicant = {};
				receiver = {};
				dayoff = 0;
				chgDate = '';
			});

			currentDate = moment(new Date()).format('YYYY-MM-DD');  //不这么写而使用js的new Date().toLocaleDateString moment会报异常警告  ...
			FC.views.custom = CustomView;
			FC.views.customMonth = {
				type: 'custom',
				duration: { months: 1 }
			}
			FC.views.customWeek = {
				type: 'custom',
				duration: { weeks: 1 }
			}

			// fetchPlanScheduInfo();
			calendar();

			//弹出框
			toastr.options = {
				closeButton: true,
				debug: false,
				progressBar: true,
				positionClass: "toast-top-center",
				onclick: null,
				showDuration: "300",
				hideDuration: "1000",
				timeOut: "2000",
				extendedTimeOut: "1000",
				showEasing: "swing",
				hideEasing: "linear",
				showMethod: "fadeIn",
				hideMethod: "fadeOut"
			};
		});